﻿/// <reference path="jquery-1.8.2.js"/>

(function ($) {

	var settings;

	var methods = {
		init: function (options) {

			settings = {
				'serviceUrl': '',
				'groupId': '',
				'huntGroupNumber': '',
				'timeToWaitInSeconds': '',
				'userName': '',
				'session': '',
				'onError': function () { },
				'onMessageReceived': function () { },
				'refreshRate': 1000,
				'topic': '',
				'showpage': 'true',
				'chatStarted': 'false',
				'isInInitialMode': 'false'
			};

			if (options) {
				$.extend(settings, options);
			}

			//a lot of required options
			if (settings.serviceUrl == "") $.error("You must declare a service URL!");
			if (settings.groupId == "") $.error("You must declare a group id!");
			if (settings.userName == "") $.error("You must declare a userName!");
			if (settings.session == "") $.error("You must declare a session!");
			if (settings.huntGroupNumber == "") $.error("You must declare a huntgroupnumber!");
			if (settings.timeToWaitInSeconds == "") $.error("You must declare a timeToWaitInSeconds!");

			var timeToWaitInMilliSeconds = settings.timeToWaitInSeconds * 1000;

			$("html").everyTime(timeToWaitInMilliSeconds, "initchat", function () {

				if (settings.chatStarted == 'false') {
					initChatSession(settings);
				} else {
					$("html").stopTime('initchat');
				}
			});

			initChatSession(settings);

			if (settings.refreshRate > 0) {
				$("html").everyTime(settings.refreshRate, function () {
					getMessagesFromServer(settings);
				});
			}

			return this;

		},
		sendToServer: function (message) {
			$.ajax({
				type: 'GET',
				url: settings.serviceUrl + 'SendInstantGroupMessage?groupId=' + settings.groupId + '&session=' + settings.session + '&message=' + message + '&r=' + Math.random(),
				dataType: 'jsonp',
				success: function (chatServiceResponse) {
					if (chatServiceResponse.HasError == "true") {
						var errorCode = chatServiceResponse.ErrorCode;
						var errorMessage = chatServiceResponse.ErrorMessage;
						var isFatal = errorCode == "SessionError";
						settings.onError.call(this, errorMessage, isFatal);

						if (isFatal) disposeTimer();
					}
				},
				error: function (xhr, ajaxOptions, thrownError) {
					settings.onError.call(this, 'Ajax error :' + ajaxOptions + ' / ' + thrownError, true);
				}
			});
		},
		dispose: function () {
			disposeTimer();
		},
		getMessages: function () {
			getMessagesFromServer(settings);
		}
	}

	$.chat = function (method) {

		// Method calling logic
		if (methods[method]) {
			return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
		} else if (typeof method === 'object' || !method) {
			return methods.init.apply(this, arguments);
		} else {
			$.error('Method ' + method + ' does not exist on jQuery.tooltip');
		}
	};

	var resizeTimerID = null;
	$(window).bind('resize', function () {
		if (resizeTimerID) clearTimeout(resizeTimerID);
		if (!canResize) {
			return;
		}
		resizeTimerID = setTimeout(resizeChat, 100);
	});
})(jQuery);

var canResize = false;
$(document).ready(function () {
	setTimeout(function () {
		canResize = true;
	}, 1000);
});

function disposeTimer() {
	$("html").stopTime();
}


function initChatSession(settings) {

	var pageParameter = "";

	if (settings.showpage == "true") {

		var url = window.opener.location.href;
		var title = '';

		$.get(url, function (response) {
			if (((/<title>(.*?)<\/title>/m).exec(response)) != null) {
				title = (/<title>(.*?)<\/title>/m).exec(response)[1];
			}

			pageParameter = "&page=" + url + "&title=" + title;
			serviceInitChatSession(settings, pageParameter);
		});

	} else {
		serviceInitChatSession(settings, pageParameter);
	}
}

function serviceInitChatSession(settings, pageParameter) {

	var serviceUrl = settings.serviceUrl + 'InitGroupChatSession?groupId=' + settings.groupId + '&session=' + settings.session + '&username=' + settings.userName + pageParameter + '&topic=' + settings.topic + '&r=' + Math.random();

	$.ajax({
		type: 'GET',
		url: serviceUrl,
		dataType: 'jsonp',
		success: function (chatServiceResponse) {
			if (chatServiceResponse.HasError == "true") {
				var errorCode = chatServiceResponse.ErrorCode;
				var errorMessage = chatServiceResponse.ErrorMessage;
				settings.onError.call(this, errorMessage, errorCode == "SessionError");
			}
		},
		error: function (xhr, ajaxOptions, thrownError) {

			settings.onError.call(this, 'Ajax error :' + ajaxOptions + ' / ' + thrownError, true);
		}
	});
}


function getMessagesFromServer(settings) {

	$.ajax({
		type: 'GET',
		url: settings.serviceUrl + 'GetMessagesFromGroup?groupId=' + settings.groupId + '&session=' + settings.session + '&r=' + Math.random(),
		dataType: 'jsonp',
		success: function (instantMessageContainer) {

			$.each(instantMessageContainer.Messages, function (index, message) {

				if (message.Type == 'InstantMessage') {
					settings.chatStarted = 'true';
				}

				settings.onMessageReceived.call(this, message.SipUri, message.Name, message.Value, message.Type);
			});
		},
		error: function (xhr, ajaxOptions, thrownError) {
			settings.onError.call(this, 'Ajax error :' + ajaxOptions + ' / ' + thrownError, true);
			disposeTimer();
		}
	});

}

var minWidth = 320;
var minHeight = 260;
function resizeChat() {
	if (!canResize) {
		return;
	}
	var width = $(window).width();
	var height = $(window).height();

	if (width > minWidth) {
		$(".presenceitem").width(width - 18);
		$("#chatWindowBody").width(width - 10);
		$("#conversation").width(width - 25);
		$("#typeMessageContainer").width(width - 10);
		$("#message").width(width - 16);
		$("#lastMessageReceived").width(width - 16);
		$(".presenceitem .buttons").width(width - 18);
	}
	if (height > minHeight) {
		$("#chatWindowBody").height(height - $(".presenceitem").height() - 95);
		$("#conversation").height($("#chatWindowBody").height() - 110);
		$("#typeMessageContainer").offset({ top: (height - $("#typeMessageContainer").height() - 10) });
		$("#lastMessageReceived").offset({ top: ($("#chatWindowBody").height() + 10) });
	}
}